<?php

namespace Chenzeming\Tools\utils;

/**
 * 一个简易token生成工具
 */

class TokenTools extends Tools
{
    /**
     * 需要加密的字符串
     * @param $data string 需要加密的数据
     * @param $key string 加密的key
     * @return false|string 加密后的字符串
     */
    public function encrypt($data,$key = '')
    {
        if (empty($data)){
            return false;
        }
        //如果不传key默认给一个key
        if (empty($key)){
            $key = 'fR8xS3U6GKdLqZvT';
        }
        if (is_array($data)){
            $data = json_encode($data,256);
        }
        $iv = base64_encode(substr($key,0,16));
        $token = openssl_encrypt($data, 'AES-256-CBC',$key,0,base64_decode($iv));
        if (empty($token)){
            return false;
        }
        return base64_encode($token);
    }

    /**
     * 解密token
     * @param $token string 需要解密的token
     * @param $key string 解密的key
     * @return false|mixed 解密出的数据
     */
    public function decrypt($token = '',$key = '')
    {
        if (empty($token)){
            return false;
        }
        //如果不传key默认给一个key 对应上面的加密
        if (empty($key)){
            $key = 'fR8xS3U6GKdLqZvT';
        }
        $iv = base64_encode(substr($key,0,16));
        $data = base64_decode($token);
        $decrypt = openssl_decrypt($data, 'AES-256-CBC', $key, 0, base64_decode($iv));
        if(!$decrypt) {
            return false;
        }
        return json_decode($decrypt,true);
    }
}